package com.sxfq.loansupermarket.backsystem.modular.remoteSynergy.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.DateTimeKit;
import com.sxfq.loansupermarket.backsystem.core.util.StringUtil;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.remoteSynergy.dao.CaseSelectionUploadDao;
import com.sxfq.loansupermarket.backsystem.modular.remoteSynergy.entity.CaseSelectionUploadInfo;
import com.sxfq.loansupermarket.backsystem.modular.remoteSynergy.entity.SearchCaseSelectionUploadInfo;
import com.sxfq.loansupermarket.backsystem.modular.remoteSynergy.entity.TongJiInfo;
import com.sxfq.loansupermarket.backsystem.modular.remoteSynergy.service.ICaseSelectionUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class CaseSelectionUploadServiceImpl implements ICaseSelectionUploadService {
    @Autowired
    private CaseSelectionUploadDao dao;

    @Autowired
    private SqlMapper sqlMapper;

    /**
     * 病例评选 界面表格数据
     *
     * @param page
     * @param searchInfo
     * @return
     */
    public List<CaseSelectionUploadInfo> selectPageListByQueryGetMap(Page<CaseSelectionUploadInfo> page, SearchCaseSelectionUploadInfo searchInfo) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("page", page);
        if (StringUtil.isNotEmpty(searchInfo.getReach())) {
            params.put("reach", searchInfo.getReach());
        }
        if (StringUtil.isNotEmpty(searchInfo.getIsUpload())) {
            if (searchInfo.getIsUpload() == 0) {
                params.put("orderBy", " order by t.create_time desc ");
            } else {
                params.put("orderBy", " order by t.apply_time desc ");
            }
            params.put("isUpload", " and t.save_status = " + searchInfo.getIsUpload() + " ");
        }
        if (StringUtil.isNotEmpty(searchInfo.getStartTime())) {
            if (searchInfo.getIsUpload() == 0) {
                params.put("startTime", " and t.create_time >= '" + searchInfo.getStartTime() + "'");
            } else {
                params.put("startTime", " and t.apply_time >= '" + searchInfo.getStartTime() + "'");
            }
        }
        if (StringUtil.isNotEmpty(searchInfo.getEndTime())) {
            if (searchInfo.getIsUpload() == 0) {
                params.put("endTime", " and t.create_time <= '" + searchInfo.getEndTime() + "'");
            } else {
                params.put("endTime", " and t.apply_time <= '" + searchInfo.getEndTime() + "'");
            }
        }
        params.put("creater", " and t.creater='" + ShiroKit.getUser().getAccount() + "'");
        params.put("startIndex", searchInfo.getStartIndex());
        params.put("limitIndex", searchInfo.getLimitIndex());
        return dao.getQueryPages(page, params);
    }

    public List<CaseSelectionUploadInfo> selectPageListByQueryGetGoBack(Page<CaseSelectionUploadInfo> page, SearchCaseSelectionUploadInfo searchInfo) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("page", page);
        if (StringUtil.isNotEmpty(searchInfo.getReach())) {
            params.put("reach", searchInfo.getReach());
        }
        if (StringUtil.isNotEmpty(searchInfo.getStartTime())) {
            params.put("startTime", " and t1.back_time >= '" + searchInfo.getStartTime() + "'");
        }
        if (StringUtil.isNotEmpty(searchInfo.getEndTime())) {
            params.put("endTime", " and t1.back_time <= '" + searchInfo.getEndTime() + "'");
        }
        params.put("creater", " and t.creater='" + ShiroKit.getUser().getAccount() + "'");
        params.put("startIndex", searchInfo.getStartIndex());
        params.put("limitIndex", searchInfo.getLimitIndex());
        return dao.selectPageListByQueryGetGoBack(page, params);
    }

    public List<CaseSelectionUploadInfo> getCaseList(int numberBars, int page) {
        String sql = "select id,applyer as creater,patient_complaints,design_think,votes," +
                "(select b.avatar from user b where b.account=a.creater) as titleImg " +
                " from case_selection_information a limit " + page + " ," + numberBars + ";";
        List<CaseSelectionUploadInfo> caseList = sqlMapper.selectList(sql, CaseSelectionUploadInfo.class);
        return caseList;
    }

    public int getQueryPagesCount(Page<CaseSelectionUploadInfo> page, SearchCaseSelectionUploadInfo searchInfo) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("page", page);
        if (StringUtil.isNotEmpty(searchInfo.getReach())) {
            params.put("reach", searchInfo.getReach());
        }
        if (StringUtil.isNotEmpty(searchInfo.getIsUpload())) {
            params.put("isUpload", " and t.save_status = " + searchInfo.getIsUpload() + " ");
        }
        if (StringUtil.isNotEmpty(searchInfo.getStartTime())) {
            if (searchInfo.getIsUpload() == 0) {
                params.put("startTime", " and t.create_time >= '" + searchInfo.getStartTime() + "'");
            } else {
                params.put("startTime", " and t.apply_time >= '" + searchInfo.getStartTime() + "'");
            }
        }
        if (StringUtil.isNotEmpty(searchInfo.getEndTime())) {
            if (searchInfo.getIsUpload() == 0) {
                params.put("endTime", " and t.create_time <= '" + searchInfo.getEndTime() + "'");
            } else {
                params.put("endTime", " and t.apply_time <= '" + searchInfo.getEndTime() + "'");
            }
        }
        params.put("creater", " and t.creater='" + ShiroKit.getUser().getAccount() + "'");
        return dao.getQueryPagesCount(page, params);
    }

    public int getByQueryGetGoBackPagesCount(Page<CaseSelectionUploadInfo> page, SearchCaseSelectionUploadInfo searchInfo) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("page", page);
        if (StringUtil.isNotEmpty(searchInfo.getReach())) {
            params.put("reach", searchInfo.getReach());
        }
        if (StringUtil.isNotEmpty(searchInfo.getStartTime())) {
            params.put("startTime", " and t1.back_time >= '" + searchInfo.getStartTime() + "'");
        }
        if (StringUtil.isNotEmpty(searchInfo.getEndTime())) {
            params.put("endTime", " and t1.back_time <= '" + searchInfo.getEndTime() + "'");
        }
        params.put("creater", " and t.creater='" + ShiroKit.getUser().getAccount() + "'");
        params.put("startIndex", searchInfo.getStartIndex());
        params.put("limitIndex", searchInfo.getLimitIndex());
        return dao.getByQueryGetGoBackPagesCount(page, params);
    }

    public List<TongJiInfo> statistics(SearchCaseSelectionUploadInfo searchInfo) {
        String contitionInfo = "save_status=0";
        String contitionInfo1 = "save_status=1";
        String contitionInfo2 = "save_status=0";
        if (StringUtil.isNotEmpty(searchInfo.getStartTime())) {
            contitionInfo += " and t.create_time >= '" + searchInfo.getStartTime() + "' ";
            contitionInfo1 += " and t.apply_time >= '" + searchInfo.getStartTime() + "' ";
            contitionInfo2 += " and t1.back_time >= '" + searchInfo.getStartTime() + "' ";
        }
        if (StringUtil.isNotEmpty(searchInfo.getEndTime())) {
            contitionInfo += " and t.create_time >= '" + searchInfo.getEndTime() + "' ";
            contitionInfo1 += " and t.apply_time >= '" + searchInfo.getEndTime() + "' ";
            contitionInfo2 += " and t1.back_time >= '" + searchInfo.getEndTime() + "' ";
        }
        if (StringUtil.isNotEmpty(searchInfo.getReach())) {
            contitionInfo += " and (t.customer_name like CONCAT('%" + searchInfo.getReach() + "%') or t.customer_phone like CONCAT('%" + searchInfo.getReach() + "%') " +
                    " or t.personacct like CONCAT('%" + searchInfo.getReach() + "%') or t.szm like CONCAT('%" + searchInfo.getReach() + "%') or t.customer_phone2 like CONCAT('%" + searchInfo.getReach() + "%')) ";
            contitionInfo1 += " and (t.customer_name like CONCAT('%" + searchInfo.getReach() + "%') or t.customer_phone like CONCAT('%" + searchInfo.getReach() + "%') " +
                    " or t.personacct like CONCAT('%" + searchInfo.getReach() + "%') or t.szm like CONCAT('%" + searchInfo.getReach() + "%') or t.customer_phone2 like CONCAT('%" + searchInfo.getReach() + "%')) ";
            contitionInfo2 += " and (t.customer_name like CONCAT('%" + searchInfo.getReach() + "%') or t.customer_phone like CONCAT('%" + searchInfo.getReach() + "%') " +
                    " or t.personacct like CONCAT('%" + searchInfo.getReach() + "%') or t.szm like CONCAT('%" + searchInfo.getReach() + "%') or t.customer_phone2 like CONCAT('%" + searchInfo.getReach() + "%')) ";
        }
        contitionInfo += " and t.creater = '" + ShiroKit.getUser().getAccount() + "' ";
        contitionInfo1 += " and t.creater = '" + ShiroKit.getUser().getAccount() + "' ";
        contitionInfo2 += " and t.creater = '" + ShiroKit.getUser().getAccount() + "' ";
        String sql = "select count(*) as countNum from (select id from case_selection_information t where " + contitionInfo + " group by t.id) t " +  //查询待提交病例
                " union all " +
                " select count(*) as countNum from (select id from case_selection_information t where " + contitionInfo1 + " group by t.id) t" + //查询已提交病例
                " union all " +
                " select count(*) as countNum from (select t.id as id from case_selection_information t left join go_back_case_info t1 on t.id=t1.backed_id where " + contitionInfo2 + ") t" ;
        return sqlMapper.selectList(sql, TongJiInfo.class);
    }

    @Transactional
    public void deleteBodyPulpCase(String id) {
        String deletesql = "delete from case_selection_information where id=" + id + "";
        sqlMapper.delete(deletesql);
    }

    public int insert(CaseSelectionUploadInfo info) {
        String birthday;
        if (info.getBirthday() == null || info.getBirthday() == "") {
            birthday = "null";
        } else {
            birthday = "'" + info.getBirthday() + "'";
        }
        String hospitalizedTime;
        if (info.getHospitalizedTime() == null || info.getHospitalizedTime() == "") {
            hospitalizedTime = "null";
        } else {
            hospitalizedTime = "'" + info.getHospitalizedTime() + "'";
        }
        String applyTime;
        if (info.getApplyTime() == null || info.getApplyTime() == "") {
            applyTime = "null";
        } else {
            applyTime = "'" + info.getApplyTime() + "'";
        }
        String time = DateTimeKit.now();
        String sql = "INSERT INTO case_selection_information (" +
                " num,szm,nationality, nation, customer_name, " +
                " id_card, birthday,insurance_state, save_status," +
                " selection_status, customer_sex, customer_age,medicalInsurance, apply_outpatient, " +
                " occupation, create_time, update_time, apply_time, " +
                " address, case_type, marital_status, medical_department," +
                " medical_type,person_weight, person_height, patient_complaints, presentIllness," +
                " pastHistory, systemic_diseases, diagnosis,treatment_advice,supple_exam_result," +
                " physical_exam, design_think, description, remarks,  " +
                " treatment_steps,BMI, hospitalized_time, creater, updater, applyer) VALUES " +
                "('" + info.getNum() + "',firstconcats('" + info.getCustomerName() + "'),'" + info.getNationality() + "','" + info.getNation() + "','" + info.getCustomerName() + "', " +
                "'" + info.getIdCard() + "'," + birthday + ", '" + info.getInsuranceState() + "', '" + info.getSaveStatus() + "'," +
                "'0','" + info.getCustomerSex() + "'," + info.getCustomerAge() + ", '" + info.getMedicalInsurance() + "','" + ShiroKit.getUser().getOutpatientName() + "'," +
                "'" + info.getOccupation() + "','" + time + "','" + time + "'," + applyTime + "," +
                "'" + info.getAddress() + "','" + info.getCaseType() + "','" + info.getMaritalStatus() + "','" + info.getMedicalDepartment() + "', " +
                "'" + info.getMedicalType() + "'," + info.getPersonWeight() + "," + info.getPersonHeight() + ",'" + info.getPatientComplaints() + "','" + info.getPresentIllness() + "'," +
                "'" + info.getPastHistory() + "','" + info.getSystemicDiseases() + "','" + info.getDiagnosis() + "', '" + info.getTreatmentAdvice() + "','" + info.getSuppleExamResult() + "'," +
                "'" + info.getPhysicalExam() + "','" + info.getDesignThink() + "','" + info.getDescription() + "','" + info.getRemarks() + "'," +
                "'', '" + info.getBMI() + "'," + hospitalizedTime + ",'" + ShiroKit.getUser().getAccount() + "','" + ShiroKit.getUser().getAccount() + "','" + info.getApplyer() + "');";
        sqlMapper.insert(sql);
        String sqls = "select * from case_selection_information where creater='" + ShiroKit.getUser().getAccount() + "'" +
                " and num='" + info.getNum() + "' limit 1";
        CaseSelectionUploadInfo cinfo = sqlMapper.selectOne(sqls, CaseSelectionUploadInfo.class);
        String upsql = "update case_selection_assistance_info set information_id=" + cinfo.getId() + ",num=null where num=" + info.getNum() + "";
        String[] rteatmentSteps = info.getTreatmentSteps().split("&&", -1);//截取字符串
        for (int i = 0; i < rteatmentSteps.length; i++) {
            String sqlc = "insert into case_selection_assistance_info (information_id,type_icon,create_time,update_time," +
                    "image_path,treatment_steps) values " +
                    "(" + cinfo.getId() + ",'treatmentSteps','" + DateTimeKit.now() + "','" + DateTimeKit.now() + "','','" + rteatmentSteps[i] + "')";
            sqlMapper.insert(sqlc);
        }
        sqlMapper.update(upsql);
        return 1;
    }

    public int update(CaseSelectionUploadInfo info) {
        String birthday;
        if (info.getBirthday() == null || info.getBirthday() == "") {
            birthday = "null";
        } else {
            birthday = "'" + info.getBirthday() + "'";
        }
        String hospitalizedTime;
        if (info.getHospitalizedTime() == null || info.getHospitalizedTime() == "") {
            hospitalizedTime = "null";
        } else {
            hospitalizedTime = "'" + info.getHospitalizedTime() + "'";
        }
        String applyTime;
        if (info.getApplyTime() == null || info.getApplyTime() == "") {
            applyTime = "null";
        } else {
            applyTime = "'" + info.getApplyTime() + "'";
        }
        String sql = "update case_selection_information set " +
                " szm=firstconcats('" + info.getCustomerName() + "'),nationality='" + info.getNationality() + "',nation='" + info.getNation() + "',customer_name='" + info.getCustomerName() + "', " +
                "id_card='" + info.getIdCard() + "',birthday=" + birthday + ",insurance_state='" + info.getInsuranceState() + "',save_status='" + info.getSaveStatus() + "'," +
                "selection_status='0',customer_sex='" + info.getCustomerSex() + "',customer_age=" + info.getCustomerAge() + ",medicalInsurance='" + info.getMedicalInsurance() + "'," +

                "occupation='" + info.getOccupation() + "',systemic_diseases='" + DateTimeKit.now() + "',apply_time=" + applyTime + "," +
                "address='" + info.getAddress() + "',case_type='" + info.getCaseType() + "',marital_status='" + info.getMaritalStatus() + "',medical_department='" + info.getMedicalDepartment() + "', " +
                "medical_type='" + info.getMedicalType() + "',person_weight=" + info.getPersonWeight() + ",person_height=" + info.getPersonHeight() + ",patient_complaints='" + info.getPatientComplaints() + "',presentIllness='" + info.getPresentIllness() + "'," +

                "pastHistory='" + info.getPastHistory() + "',systemic_diseases='" + info.getSystemicDiseases() + "',diagnosis='" + info.getDiagnosis() + "',treatment_advice='" + info.getTreatmentAdvice() + "',supple_exam_result='" + info.getSuppleExamResult() + "'," +

                "physical_exam='" + info.getPhysicalExam() + "',design_think='" + info.getDesignThink() + "',description='" + info.getDescription() + "',remarks='" + info.getRemarks() + "'," +
                "treatment_steps='" + info.getTreatmentSteps() + "',BMI='" + info.getBMI() + "',hospitalized_time=" + hospitalizedTime + "," +
                "updater='" + ShiroKit.getUser().getAccount() + "',applyer='" + info.getApplyer() + "' where id=" + info.getId() + ";";

        String sql2 = "delete from case_selection_assistance_info where information_id='" + info.getId() + "' and type_icon='treatmentSteps' ";
        sqlMapper.delete(sql2);
        String[] rteatmentSteps = info.getTreatmentSteps().split("&&", -1);//截取字符串
        for (int i = 0; i < rteatmentSteps.length; i++) {
            String sqlc = "insert into case_selection_assistance_info (information_id,type_icon,create_time,update_time," +
                    "image_path,treatment_steps) values " +
                    "(" + info.getId() + ",'treatmentSteps','" + DateTimeKit.now() + "','" + DateTimeKit.now() + "','','" + rteatmentSteps[i] + "')";
            sqlMapper.insert(sqlc);
        }
        return sqlMapper.insert(sql);
    }
}